package com.xiaobai.myblog.controller;

import cn.hutool.json.JSONObject;
import com.xiaobai.myblog.common.lang.Result;
import com.xiaobai.myblog.util.FileNameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

@RestController
@RequestMapping("file")
public class FileController {
    @Value("${file.upload.url}")
    private String uploadFilePath;
    @RequestMapping("/upload")
    public Result httpUpload(@RequestParam("files") MultipartFile files[]){
        ArrayList<String> images = new ArrayList<>();

        for(int i=0;i<files.length;i++){
            String originalFilename = files[i].getOriginalFilename();  // 文件名
            // 拼写成唯一的文件名
            String fileName = FileNameUtils.createFileName() + FileNameUtils.getFileExtension(originalFilename);
            File dest = new File(uploadFilePath +'/'+ fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                files[i].transferTo(dest);
                images.add("/picture/"+fileName);
            } catch (Exception e) {
                return Result.fail("文件上传失败");
            }
        }
        HashMap<Object, Object> map = new HashMap<>();
        map.put("images", images);
        return Result.succ("文件上次成功", map);
    }
}
